﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OracleClient;
using System.Runtime.Serialization;
using System.Data;

namespace MM.Common.IRemoteDataBase
{
    [DataContract]
    public class OraParm
    {
        // Fields
        [DataMember]
        public ParameterDirection Direction;
        [DataMember]
        public string Name;
        [DataMember]
        public string Type;
        [DataMember]
        public string Value;

        // Methods
        public OraParm()
        {
        }

        public OraParm(string parmName, object parmValue, ParameterDirection parmDirection)
        {
            this.Name = parmName;
            this.Direction = parmDirection;
            this.Type = parmValue.GetType().ToString();
            if (parmValue.GetType() == System.Type.GetType("System.Byte[]"))
            {
                this.Value = Convert.ToBase64String((byte[])parmValue);
            }
            else
            {
                this.Value = parmValue.ToString();
            }
        }

        public OracleParameter ToOracleParameter()
        {
            OracleParameter parameter = new OracleParameter
            {
                ParameterName = this.Name,
                Direction = this.Direction
            };
            switch (this.Type)
            {
                case "System.Int32":
                case "System.Int16":
                case "System.Single":
                case "System.Double":
                case "System.Decimal":
                    parameter.OracleType = OracleType.Number;
                    if (!(this.Value == string.Empty))
                    {
                        parameter.Value = decimal.Parse(this.Value);
                        return parameter;
                    }
                    parameter.Value = DBNull.Value;
                    return parameter;

                case "System.DateTime":
                    parameter.OracleType = OracleType.DateTime;
                    parameter.Value = DateTime.Parse(this.Value);
                    return parameter;

                case "System.Byte[]":
                    parameter.OracleType = OracleType.Blob;
                    parameter.Value = Convert.FromBase64String(this.Value);
                    return parameter;

                case "System.Boolean":
                    parameter.OracleType = OracleType.Cursor;
                    return parameter;
            }
            parameter.OracleType = OracleType.VarChar;
            if (this.Value == string.Empty)
            {
                parameter.Value = DBNull.Value;
                return parameter;
            }
            parameter.Value = this.Value;
            return parameter;
        }
    }
}
